# -*- coding:utf-8 -*-

from com.zzh.utils.dbUtils import MysqlUtils
from com.zzh.utils.table2JSON import Table2Json


class UnitDao(object):
    def __init__(self):
        self.conn = MysqlUtils.get_mysql_connections()

    def add_unit_info(self, new_id, unit_info):
        cur = self.conn.cursor()
        unit_id = new_id
        unit_name = unit_info['unit_name']
        unit_job = unit_info['unit_job']
        unit_address = unit_info['unit_address']
        unit_code = unit_info['unit_code']

        unit_province = unit_info['unit_province']
        unit_city = unit_info['unit_city']
        unit_town = unit_info['unit_town']

        unit_busness = unit_info['unit_busness']

        sql = "insert into zzh_unit (unit_id,unit_name,unit_job,unit_address,unit_busness,unit_code," \
              "unit_province,unit_city,unit_town) " \
              "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        result = cur.execute(sql, [unit_id,unit_name, unit_job, unit_address, unit_busness,unit_code,
                                   unit_province,unit_city,unit_town])
        self.conn.commit()
        sql2 = "update zzh_user set user_type='2' WHERE user_id=%s"
        cur.execute(sql2, [new_id])
        self.conn.commit()

        cur.close()
        self.conn.close()
        return result

    def update_unit(self,unit_id, unit_info):
        cur = self.conn.cursor()
        unit_name = unit_info['unit_name']
        unit_job = unit_info['unit_job']
        unit_address = unit_info['unit_address']
        unit_email = unit_info['unit_email']
        unit_busness = unit_info['unit_busness']
        unit_img = unit_info['unit_img']
        unit_code = unit_info['unit_code']

        unit_province = unit_info['unit_province']
        unit_city = unit_info['unit_city']
        unit_town = unit_info['unit_town']

        sql = "update zzh_unit set unit_name=%s,unit_job=%s,unit_address=%s,unit_email=%s,unit_busness=%s,unit_img=%s,unit_code=%s," \
              "unit_province=%s,unit_city=%s,unit_town=%s " \
              "WHERE unit_id=%s "
        result = cur.execute(sql, [unit_name, unit_job, unit_address, unit_email, unit_busness, unit_img,unit_code,
                                   unit_province,unit_city,unit_town,unit_id])
        self.conn.commit()
        cur.close()
        self.conn.close()
        return result

    def query_unit_info(self, unit_id):
        cur = self.conn.cursor()
        sql = "select * from zzh_unit where unit_id=%s"
        result = cur.execute(sql, [unit_id])
        unit_list = cur.fetchall()
        unit_json = Table2Json.unit_list_to_json(unit_list)
        return unit_json

    def query_unit_by_id(self,unit_id):
        cur = self.conn.cursor()
        sql = "select * from zzh_unit where unit_id=%s"
        result = cur.execute(sql, [unit_id])
        unit_list = cur.fetchone()
        return unit_list